<!-- Token调试组件 - Instagram风格 -->
<template>
  <div class="token-debugger">
    <div class="instagram-card">
      <div class="card-header">
        <div class="header-avatar">
          <i class="el-icon-key"></i>
        </div>
        <div class="header-info">
          <div class="username">Token调试器</div>
          <div class="location">子应用</div>
        </div>
        <div class="header-actions">
          <el-tooltip content="刷新Token信息" placement="top">
            <el-button type="text" @click="updateTokenInfo" class="refresh-btn">
              <i class="el-icon-refresh"></i>
            </el-button>
          </el-tooltip>
        </div>
      </div>
      
      <div class="card-content">
        <div class="token-status-bar">
          <div class="status-indicator" :class="{ 'status-valid': !isExpired, 'status-expired': isExpired }"></div>
          <div class="status-text">{{ isExpired ? 'Token已过期' : 'Token有效' }}</div>
          <div class="time-display">{{ currentTimeFormatted }}</div>
        </div>
        
        <div class="token-field">
          <div class="field-label">
            <span>Access Token</span>
            <div class="token-actions">
              <el-tooltip content="复制" placement="top">
                <el-button type="text" @click="copyToken('auth')" class="action-btn">
                  <i class="el-icon-copy-document"></i>
                </el-button>
              </el-tooltip>
            </div>
          </div>
          <el-input
            v-model="editableAuthToken"
            type="textarea"
            :rows="3"
            placeholder="无Access Token"
            @change="updateAuthToken"
          />
        </div>
        
        <div class="token-field">
          <div class="field-label">
            <span>Refresh Token</span>
            <div class="token-actions">
              <el-tooltip content="复制" placement="top">
                <el-button type="text" @click="copyToken('refresh')" class="action-btn">
                  <i class="el-icon-copy-document"></i>
                </el-button>
              </el-tooltip>
            </div>
          </div>
          <el-input
            v-model="editableRefreshToken"
            type="textarea"
            :rows="2"
            placeholder="无Refresh Token"
            @change="updateRefreshToken"
          />
        </div>
        
        <div class="token-info-grid">
          <div class="info-item">
            <div class="info-label">过期时间</div>
            <div class="info-value">{{ expiryTimeFormatted }}</div>
          </div>
          <div class="info-item">
            <div class="info-label">剩余时间</div>
            <div class="info-value" :class="{ 'countdown-warning': remainingSeconds < 60, 'countdown-danger': remainingSeconds < 30 }">
              {{ remainingSeconds }}秒
            </div>
          </div>
        </div>
        
        <div v-if="tokenInfo.payload" class="token-payload">
          <div class="payload-header">
            <span>Token负载</span>
            <el-tooltip content="复制负载" placement="top">
              <el-button type="text" @click="copyPayload" class="action-btn">
                <i class="el-icon-copy-document"></i>
              </el-button>
            </el-tooltip>
          </div>
          <pre>{{ JSON.stringify(tokenInfo.payload, null, 2) }}</pre>
        </div>
      </div>
      
      <div class="card-footer">
        <div class="footer-stats">
          <div class="stat-item">
            <i class="el-icon-time"></i>
            <span>{{ tokenInfo.expiresAt ? new Date(tokenInfo.expiresAt).toLocaleTimeString() : '未知' }}</span>
          </div>
          <div class="stat-item">
            <i class="el-icon-user"></i>
            <span>{{ tokenInfo.payload?.username || '未知用户' }}</span>
          </div>
        </div>
        <div class="footer-actions">
          <el-button type="primary" @click="testApi" :disabled="isExpired">
            测试API请求
          </el-button>
          <el-button type="success" @click="applyTokens">
            应用Token
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import TokenManager, { TOKEN_KEYS } from '../utils/tokenManager'
import { ElMessage } from 'element-plus'
import http from '../utils/request'

// 响应式数据
const tokenInfo = ref(TokenManager.getTokenInfo())
const updateInterval = ref<number | null>(null)
const remainingSeconds = ref(0)
const currentTime = ref(new Date())

// 可编辑的token
const editableAuthToken = ref(tokenInfo.value.authToken || '')
const editableRefreshToken = ref(tokenInfo.value.refreshToken || '')

// 计算属性
const expiryTimeFormatted = computed(() => {
  if (!tokenInfo.value.expiresAt) return '未设置'
  return new Date(tokenInfo.value.expiresAt).toLocaleString()
})

const currentTimeFormatted = computed(() => {
  return currentTime.value.toLocaleString()
})

const isExpired = computed(() => {
  if (!tokenInfo.value.expiresAt) return true
  return Date.now() > tokenInfo.value.expiresAt
})

// 方法
const updateTokenInfo = () => {
  tokenInfo.value = TokenManager.getTokenInfo()
  currentTime.value = new Date()
  
  // 更新可编辑token
  editableAuthToken.value = tokenInfo.value.authToken || ''
  editableRefreshToken.value = tokenInfo.value.refreshToken || ''
  
  // 计算剩余时间
  const expiry = tokenInfo.value.expiresAt
  if (expiry) {
    const remaining = Math.max(0, Math.floor((expiry - Date.now()) / 1000))
    remainingSeconds.value = remaining
  } else {
    remainingSeconds.value = 0
  }
}

const testApi = async () => {
  try {
    const response = await http.get('/api/auth-center/profile', {}, false, true)
    ElMessage.success('API请求成功')
    console.log('API响应:', response)
  } catch (error) {
    console.error('API请求失败', error)
    ElMessage.error('API请求失败')
  }
}

const copyToken = (type: 'auth' | 'refresh') => {
  const token = type === 'auth' ? tokenInfo.value.authToken : tokenInfo.value.refreshToken
  if (token) {
    navigator.clipboard.writeText(token)
      .then(() => ElMessage.success(`已复制${type === 'auth' ? 'Access' : 'Refresh'} Token`))
      .catch(() => ElMessage.error('复制失败，请手动复制'))
  } else {
    ElMessage.warning(`没有${type === 'auth' ? 'Access' : 'Refresh'} Token可复制`)
  }
}

const copyPayload = () => {
  if (tokenInfo.value.payload) {
    navigator.clipboard.writeText(JSON.stringify(tokenInfo.value.payload, null, 2))
      .then(() => ElMessage.success('已复制Token负载'))
      .catch(() => ElMessage.error('复制失败，请手动复制'))
  }
}

const updateAuthToken = () => {
  // 不立即应用，等用户点击应用按钮
  console.log('Access Token已编辑，等待应用')
}

const updateRefreshToken = () => {
  // 不立即应用，等用户点击应用按钮
  console.log('Refresh Token已编辑，等待应用')
}

const applyTokens = () => {
  try {
    // 应用编辑后的token - 直接写入localStorage
    if (editableAuthToken.value) {
      localStorage.setItem(TOKEN_KEYS.AUTH_TOKEN, editableAuthToken.value)
    }
    
    if (editableRefreshToken.value) {
      localStorage.setItem(TOKEN_KEYS.REFRESH_TOKEN, editableRefreshToken.value)
    }
    
    // 更新token信息
    updateTokenInfo()
    ElMessage.success('Token已成功应用')
  } catch (error) {
    console.error('应用Token失败', error)
    ElMessage.error('应用Token失败')
  }
}

// 生命周期钩子
onMounted(() => {
  // 每秒更新一次token信息
  updateInterval.value = window.setInterval(() => {
    updateTokenInfo()
  }, 1000)
})

onUnmounted(() => {
  // 清除定时器
  if (updateInterval.value !== null) {
    clearInterval(updateInterval.value)
  }
})
</script>

<style scoped>
.token-debugger {
  margin-bottom: 20px;
}

.instagram-card {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 2px rgba(0,0,0,0.2);
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color);
}

.card-header {
  display: flex;
  align-items: center;
  padding: 14px 16px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.header-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: var(--el-fill-color-light);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  color: var(--el-color-primary);
  font-size: 18px;
}

.header-info {
  flex: 1;
}

.username {
  font-weight: 600;
  font-size: 14px;
  color: var(--el-text-color-primary);
}

.location {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.header-actions {
  color: var(--el-text-color-primary);
}

.card-content {
  padding: 0;
}

.token-status-bar {
  display: flex;
  align-items: center;
  padding: 10px 16px;
  background: var(--el-fill-color-light);
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.status-indicator {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  margin-right: 8px;
}

.status-valid {
  background: var(--el-color-success);
}

.status-expired {
  background: var(--el-color-danger);
}

.status-text {
  font-size: 13px;
  font-weight: 500;
  flex: 1;
}

.time-display {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.token-field {
  padding: 16px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.field-label {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.token-actions {
  display: flex;
}

.action-btn {
  padding: 2px;
}

.token-info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  padding: 16px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.info-item {
  padding: 0 8px;
}

.info-label {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-bottom: 4px;
}

.info-value {
  font-size: 14px;
  font-weight: 500;
}

.countdown-warning {
  color: var(--el-color-warning);
}

.countdown-danger {
  color: var(--el-color-danger);
}

.token-payload {
  padding: 16px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.payload-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 500;
}

.token-payload pre {
  background: var(--el-fill-color-light);
  padding: 12px;
  border-radius: 4px;
  margin: 0;
  font-size: 12px;
  overflow: auto;
  max-height: 200px;
  border: 1px solid var(--el-border-color-lighter);
}

.card-footer {
  padding: 16px;
  border-top: 1px solid var(--el-border-color-lighter);
}

.footer-stats {
  display: flex;
  margin-bottom: 16px;
}

.stat-item {
  display: flex;
  align-items: center;
  margin-right: 16px;
  font-size: 13px;
  color: var(--el-text-color-secondary);
}

.stat-item i {
  margin-right: 4px;
}

.footer-actions {
  display: flex;
  justify-content: space-between;
}

.refresh-btn {
  font-size: 16px;
}
</style> 